package im.notify.server;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.filter.keepalive.KeepAliveFilter;
import org.apache.mina.filter.keepalive.KeepAliveMessageFactory;
import org.apache.mina.filter.keepalive.KeepAliveRequestTimeoutHandler;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.DefaultSocketSessionConfig;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;


public class MinaServer {
	
	NioSocketAcceptor acceptor;
	
	private static MinaServer mina = new MinaServer();
	public static MinaServer share()
	{
		return mina;
	}
	
	public MinaServer()
	{
		
	}
	
	public void init()
	{
		acceptor = new NioSocketAcceptor();  
        acceptor.getSessionConfig().setReadBufferSize(1024);  
        ((DefaultSocketSessionConfig)acceptor.getSessionConfig()).setTcpNoDelay(true);
        acceptor.getFilterChain().addLast("executor",new ExecutorFilter());  
        acceptor.getFilterChain().addLast("logger",new LoggingFilter());  
        acceptor.getFilterChain().addLast("codec",new ProtocolCodecFilter(new MyTextLineFactory()));  
        KeepAliveMessageFactory heartBeatFactory = new KeepAliveMessageFactoryImpl();  
        KeepAliveFilter keepAliveFilter = new KeepAliveFilter(heartBeatFactory,IdleStatus.BOTH_IDLE,KeepAliveRequestTimeoutHandler.CLOSE,60,30);  
        keepAliveFilter.setForwardEvent(true);  
        acceptor.getFilterChain().addLast("heartbeat",keepAliveFilter); 
        IoHandler ioHandler = new IoHandler();
        acceptor.setHandler(ioHandler);  
        
        try {
			acceptor.bind(new InetSocketAddress(9999));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void unbind()
	{
		acceptor.unbind();
	}

}
